﻿using System;
using System.Linq;
using CardPlay.Model.ActionModel;

namespace CardPlay.Model.GameModel.Actions
{
    public class DealAction : GameAction
    {
        private readonly MovePileAction _moveAction;
        private readonly IAction _flipAction;
        private int _previousStackLimit;

        public DealAction(CardGame cardGame, PartLocation from, PartLocation to)
            : base(cardGame, from)
        {
            Guard.Against<ArgumentException>(cardGame.PileAt(from).IsEmpty, "Can't deal from an empty pile.");

            var fromPile = cardGame.PileAt(from);
        
            from.Index = Math.Max(0, fromPile.Count - cardGame.CardsPerDeal);
            to.Index = cardGame.PileAt(to).Count - 1;
            
            _moveAction = new MovePileAction(cardGame, from, to);
            _flipAction = new ComplexAction(
                _moveAction.PileBeingMoved.Where(card => !card.IsFaceUp)
                .Select(card => new FlipCardAction(cardGame, fromPile.LocationOf(card))));
        }
        
        protected override void OnExecute()
        {
            _previousStackLimit = _moveAction.TargetPile.StackLimit;
            _moveAction.TargetPile.StackLimit = _moveAction.TargetPile.Count;

            //_moveAction.PileBeingMoved.Invert();
            _flipAction.Execute();
            _moveAction.Execute();
        }

        protected override void OnReverse()
        {
            _moveAction.TargetPile.StackLimit = _previousStackLimit;

            //_moveAction.PileBeingMoved.Invert();
            _moveAction.Reverse();
            _flipAction.Reverse();
        }
    }
}
